package com.hk.aop;

import com.hk.commons.ConstantPush;
import com.hk.commons.enm.MqEventType;
import com.hk.commons.utils.MsgTypeConstants;
import com.hk.commons.vo.MqCenterMsg;
import com.hk.service.IPush;
import com.hk.service.kyc.ICoupon;
import com.hk.service.mq.IMq;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hk.commons.StringHelper;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.service.IPointsHistory;
import com.hk.service.order.IPayment;
import com.hk.service.sys.ISysUser;

import java.time.LocalDate;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Aspect
public class UserAop {

	private Logger logger = LoggerFactory.getLogger(UserAop.class);

	@Autowired
	IPointsHistory pointsHistoryImpl;

	@Autowired
	IPayment payService;

	@Autowired
	ISysUser userService;

	@Autowired
	private IPush pushService;

	@Autowired
	ICoupon couponService;

    @Autowired
    private IMq mqService;

	@Pointcut("execution(* com.hk.service.sys.impl.SysUserImpl.add(..))")
	private void pointCutAddUser() {
	}

	@Pointcut("execution(* com.hk.service.order.impl.PaymentImpl.add(..))")
	private void pointCutTieCard() {
	}

	/**
	 * After 用户注册成功之后调用该方法, 增加1个推荐用户数
	 * 
	 * @param
	 */
	@AfterReturning(pointcut = "pointCutAddUser()", returning = "returnValue")
	public Boolean updUserInfo(JoinPoint point, Object returnValue) {
		System.out.println("用户注册成功之后调用该方法");
		System.out.println("@AfterReturning：返回值为：" + returnValue);
		Long userId = (Long) returnValue;
		SysUser user = this.userService.findById(userId);

		ExecutorService executor = Executors.newFixedThreadPool(1);

		Runnable task = () -> {

			logger.info("注册成功后 开始送加息券 userId={}",userId);
            sendCard(userId);

			logger.info("注册成功后 开始推送给理财师 userId={}",userId);
            sendPushToFinancial(userId);

            String message = String.format("恭喜您，注册成功！为了不影响您的投资，请到【我的银行卡】中进行实名认证并绑卡");
            UserAop.this.pushService.jgPushCustomerMsg(message, "注册成功", null, null, null, user.getName(), ConstantPush.PUSH_MENU, MsgTypeConstants.APPOINTMENT);
        };
		executor.execute(task);
		executor.shutdown();
		return true;
	}

	/**
	 * After 用户绑卡后调用该方法, 增加1个推荐用户数
	 * 
	 * @param
	 */
	@AfterReturning(pointcut = "pointCutTieCard()", returning = "returnValue")
	public Boolean updUserInfoAfterTieCard(JoinPoint point, Object returnValue) {
		logger.info("用户绑卡成功之后调用该方法");
		logger.info("@AfterReturning：返回值为：" + returnValue);
		Long paymentId = (Long) returnValue;

		Payment payment = payService.findById(paymentId);
		if (payment != null) {
			Long userId = payment.getUserId();
			SysUser user = userService.findById(userId);
			if(user != null){
				user.setTieCard(1);
				userService.update(user);
				logger.info("用户绑卡成功之后设置用户的绑卡状态为已绑卡");
			}
		}
		return true;
	}

    /**
     * 该方法用于当用户填写推荐码之后，给用户赠送加息券
     *
     * @param userId
     */
    private void sendCard(Long userId) {
        SysUser user = userService.findById(userId);

        // 01 如果用户不存在，或推荐码为空，则直接退出
        if (user == null || StringHelper.isEmpty(user.getRecommendCode())) {
            return;
        }

        // 02 如果填的推荐码不是正确的理财师，则直接退出
        SysUser finUser = userService.getByPhoneNum(user.getRecommendCode());
        if (finUser == null || finUser.getIsInside() == null || finUser.getIsInside() != 1) {
            return;
        }

        String dispatchEvent = MqEventType.USER_REGISTRATION.toString();
        MqCenterMsg msg = MqCenterMsg.getMqCenterMsg(user.getId(), dispatchEvent);

        mqService.setMessage(MqCenterMsg.CENTER_QUEUE_NAME, msg);
    }

	private void sendPushToFinancial(Long userId) {

		SysUser user = userService.findById(userId);
		if(user == null){
			return ;
		}

		//客户手机号
		String custPhone = user.getName();

		//理财师手机号
		String recommendCode = user.getRecommendCode();

		SysUser finUser = null;

		if(StringHelper.isNotEmpty(recommendCode)){
			finUser = userService.getByPhoneNum(recommendCode);
		}else{
			return;
		}


		if (finUser != null) {
			int isInside = finUser.getIsInside();
			if (isInside == 1 ) {// 已经是内部理财师

				String msg = ConstantPush.PUSH_REGIST_START + custPhone
						+ ConstantPush.PUSH_REGIST_END;
				pushService.jgPushMsg(msg, null, null, null, recommendCode,
						ConstantPush.PUSH_MENU_REGISTER, MsgTypeConstants.REGISTER);
			}
		}

	}
}

